<?php
/**
 * Created by PhpStorm.
 * User: ADMIN
 * Date: 2021/6/20
 * Time: 16:39
 */

namespace app\api\service;

use app\common\model\ChangeFunction;
use app\common\model\Variable;
use Fairy\MhtFileMaker;
use think\Config;
use app\common\model\Enterprise;
use fast\Random;
use PhpOffice\PhpWord\TemplateProcessor;

/**
 * 聚合数据api
 * Class JuHe
 * @package app\api\service
 */
class JuHe extends Base
{
    public $money = 0;
    public $business_information_key = '';
    public $precise_information_key = '';
    public $business_information_ok = 0;
    public $precise_information_ok = 0;

    public function __construct()
    {
        $site = config('site');
        $this->money = $site['search_consume_money'];
        $this->business_information_key = $site['business_information_key'];
        $this->precise_information_key = $site['precise_information_key'];
        $this->business_information_ok = $site['business_information_ok'];
        $this->precise_information_ok = $site['precise_information_ok'];
    }

    /**
     * 搜索
     * @param $postData
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function search($postData)
    {
        if (!($postData['userInfo']['money'] > $this->money || (!empty($postData['userInfo']['level']) && !empty($postData['userInfo']['level_duedate']) && $postData['userInfo']['level_duedate'] > time()))) {
            $this->setError('请先购买金豆');
            return false;
        }
        $postData['link'] = "http://japi.juhe.cn/enterprise/simpleList";


        // 新增搜索记录
        $this->addSearchRecord($postData);

        // 调用企业工商信息api
        if ($this->business_information_ok == 0) {
            $data = $this->businessInformation($postData);
            if (!$data) return $data;

            // 保存搜索数据
            $this->saveBusinessInformation($data);

            // 扣除金豆
            $this->consumeMoney($postData, $data);
        }

        // 测试数据
        $data = db('enterprise')
            ->where("name", 'like', "%{$postData['keywords']}%")
            ->whereOr('credit_no', 'like', "%{$postData['keywords']}%")
            ->field("id, name, credit_no, oper_name, status,if(addresses='', '无',addresses) as addresses, regist_capi_new, partners,
                scope, regist_capi_new, currency_unit")
            ->order('id desc')
            ->limit(5)
            ->select();
        if(!empty($data))
        {
            foreach ($data as &$v)
            {
                // 出资时间
                if(!empty($v['partners']))
                {
                    $partners = json_decode($v['partners']);
                    $should_capi_date = $partners[0]->should_capi_items[0]->should_capi_date;
                }
                $v['should_capi_date'] = isset($should_capi_date) ? $should_capi_date : '';
            }
        }

        return $data;
    }

    /**
     * 扣除金豆
     * @param $postData
     * @param $data
     * @throws \think\Exception
     */
    public function consumeMoney($postData, $data)
    {
        if ($data && !empty($this->money)) {
            if (!(!empty($postData['userInfo']['level']) && !empty($postData['userInfo']['level_duedate']) && $postData['userInfo']['level_duedate'] > time())) {
                // 不是会员 扣除金豆
                db('user')
                    ->where("id={$postData['userInfo']['user_id']}")
                    ->setDec('money', $this->money);

                // 扣除金豆记录
                db('user_money_log')
                    ->insert([
                        'user_id' => $postData['userInfo']['user_id'],
                        'money' => $this->money,
                        'before' => $postData['userInfo']['money'],
                        'after' => $postData['userInfo']['money'] - $this->money,
                        'memo' => "会员{$postData['userInfo']['mobile']}搜索企业信息{$postData['keywords']}扣除金豆{$this->money}",
                    ]);
            }
        }
    }

    /**
     * 保存企业信息
     * @param $data
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function saveBusinessInformation($data)
    {
        if ($data) {
            foreach ($data as $v) {
                $count = db('enterprise')->where("number='{$v["id"]}'")->count();
                if (!empty($count)) {
                    // 数据存在修改
                    db('enterprise')
                        ->where("number='{$v["id"]}'")
                        ->update([
                            'name' => $v['name'],
                            'number' => $v['id'],
                            'start_date' => $v['start_date'],
                            'oper_name' => $v['oper_name'],
                            'reg_no' => $v['reg_no'],
                            'credit_no' => $v['credit_no'],
                        ]);
                } else {
                    db('enterprise')
                        ->insert([
                            'name' => $v['name'],
                            'number' => $v['id'],
                            'start_date' => $v['start_date'],
                            'oper_name' => $v['oper_name'],
                            'reg_no' => $v['reg_no'],
                            'credit_no' => $v['credit_no'],
                        ]);
                }
            }
        }
    }

    /**
     * 访问企业工商信息接口
     * @param $postData
     * @return bool
     */
    public function businessInformation($postData)
    {
        $url = $postData['link'] . '?keyword=' . urlencode($postData['keywords']) . '&key=' . $this->business_information_key;
        $res = json_decode(curl_get($url), true);
        if ($res['error_code'] != 0) {
            $this->setError($res['reason']);
            return false;
        }

        return $res['result']['data']['items'];
    }

    /**
     * 增加搜索记录
     * @param $postData
     */
    public function addSearchRecord($postData)
    {
        $times = time();

        $srData = [
            'user_id' => $postData['userInfo']['user_id'],
            'ip' => $postData['ip'],
            'keywords' => $postData['keywords'],
            'link' => $postData['link'],
            'createtime' => $times,
            'updatetime' => $times,
        ];
        db('search_record')->insert($srData);
    }

    /**
     * 变更
     */
    public function change($postData)
    {
        // 公司信息
        $postData['enterprise'] = db('enterprise')->where("id={$postData['companyId']}")->field('credit_no, name')->find();

        // 公司精确信息查询
        $postData['link'] = "http://japi.juhe.cn/enterprise/getDetailByName";
        if ($this->precise_information_ok == 0) {
            // 企业信息精确查询
            $data = $this->getEnterpriseDetail($postData);

            // 保存企业详细数据
            $this->saveEnterprise($data, $postData);
        }

        // 生成文档
        if (!$templateFile = $this->createWorld($postData)) return false;
        return ['file' => $templateFile];
    }

    /**
     * 生成文档
     * @param $postData
     * @return bool|string
     */
    public function createWorld($postData)
    {
        // 生成word文档
        if (!$changeFunction = $this->realWorld($postData)) return false;

        // 合并模板
        if (!$templateFile = $this->mergeTemplate($postData, $changeFunction)) return false;

        //合并之后删除无用文档
        if (!$this->deleteUselessFile($changeFunction)) return false;

        // 生成变更记录
        $data = [
            'user_id' => $postData['userInfo']['id'],
            'enterprise_id' => $postData['companyId'],
            'change_category' => json_encode($postData['changCategory']),
            'templateFile' => $templateFile,
            'createtime' => time(),
            'updatetime' => time(),
        ];
        db('change')->insert($data);

        return $templateFile;
    }

    /**
     * @param $constitution 自然人投资或控股章程0    自然人独资章程1    公司独资章程2
     * @param $documentStrArr 原变更文档数据
     */
    public function selectDocumentStrArr($constitution, $documentStrArr)
    {
        foreach ($documentStrArr as $k=>$v)
        {
            if($constitution == 0 && ($v['template']['name'] == '自然人独资章程' || $v['template']['name'] == '公司独资章程')) unset($documentStrArr[$k]);
            if($constitution == 1 && ($v['template']['name'] == '自然人投资或控股章程' || $v['template']['name'] == '公司独资章程')) unset($documentStrArr[$k]);
            if($constitution == 2 && ($v['template']['name'] == '自然人投资或控股章程' || $v['template']['name'] == '自然人独资章程')) unset($documentStrArr[$k]);
        }
        sort($documentStrArr);
        return $documentStrArr;
    }

    /**
     * 生成真实文档
     * @param $postData
     * @param $templateFile
     */
    public function realWorld($postData)
    {
        // 模板功能数组
        $changeCategoryIdsArr = array_column($postData['changCategory'], 'id');
        sort($changeCategoryIdsArr);
        $changeCategoryIds = implode(',', $changeCategoryIdsArr);
        $changeFunction = ChangeFunction::getInfo("change_category_ids in ({$changeCategoryIds})");
        $sortArr = array_column($changeFunction['documentStrArr'], 'sort');
        array_multisort($sortArr, SORT_ASC, $changeFunction['documentStrArr']);

        /*--------公司信息--------*/
        $info = Enterprise::getInfo("id={$postData['companyId']}");
        if (strstr($info['name'], '有限合伙')) {
            $this->setError('暂不支持有限合伙变更');
            return false;
        }
        if (empty($info['partners']) || empty($info['employees'])) {
            $this->setError('公司信息不完整');
            return false;
        }

        /*--------判断选择股东决定模板还是股东会决议模板 为true选择股东会决议，并且属于投资控股 id=7投资控股 id=8独资--------*/
        $isDecision = $this->isDecision($info);
        foreach ($changeFunction['documentStrArr'] as $k => $v) {
            // 为true时是股东会决议，股东会决议保留，删除股东决定
            if ($isDecision) {
                if ($v['template']['name'] == '股东决定') unset($changeFunction['documentStrArr'][$k]);
            } else {
                if ($v['template']['name'] == '股东会决议') unset($changeFunction['documentStrArr'][$k]);
            }
        }

        /*--------委派或者选举 独资委派 其它选举--------*/
        $generationMode = !$isDecision ? '委派' : '选举';


        /*--------基础变量替换--------*/
        $basicTypeArr = [];
        $variableList = Variable::getAll();
        foreach ($variableList['list'] as $v) {
            // 营业期限 特殊处理
            if (strstr($v['relation_key'], '+')) {
                $arr = explode('+', $v['relation_key']);
                $arrStr = '';
                foreach ($arr as $k1 => $v1) {
                    $arrStr .= $k1 == 0 ? $info[$v1] : '~' . $info[$v1];
                }
                $basicTypeArr['${' . $v['value'] . '}'] = $arrStr;
            } else {
                $basicTypeArr['${' . $v['value'] . '}'] = $info[$v['relation_key']];
            }
        }

        /**
         * 备案事项
         * 变更事项，原登记内容，变更后等级内容
         * 公司名称、公司住所、法人变更、注册资本、公司类型、有限责任公司股东（股东姓名或者名称）、股份有限公司发起人的姓名或者名称
         */
        $changeTypeArr = [];

        /**
         * 其它备案事项
         * 变更事项，原登记内容，变更后等级内容
         * 经营范围、经营场所、营业期限/经营期限、出资时间、出资方式、投资总额（限外资公司）
         */
        $recordTypeArr = [];

        $descRowArr = [];
        $commentRowArr = [];

        // 股东变更时 第二份股东决定或股东会决议
        $commentRowArr_1 = [];

        $rules_shareholder_row_arr = [];
        $rules_shareholder_arr = [];
        $shareholderRowArr = [];
        $shareholderRowArr_1 = [];

        // 股权转让协议
        $equity_transfer_arr = [];

        // 是否有章程修正案 如果有需要在股东或股东会协议多加一句话 修改公司章程相应条款
        $isZhangcheng = 0;

        // 公司原来的经理信息
        $manager = [];
        // 公司原来的监事信息
        $supervisor = [];
        foreach ($info['employees'] as $v) {
            if (strstr($v['job_title'], '经理')) {
                $manager = $v;
            }
            if (strstr($v['job_title'], '监事')) {
                $supervisor = $v;
            }
        }

        /*--------股东决定或股东会决议内容--------*/
        $basicTypeArr['${companyAddress}'] = $info['addresses'];
        //股东信息
        $basicTypeArr['shareholder'] = '';
        $basicTypeArr['shareholderOld'] = '';
        $basicTypeArr['shareholder_1'] = '';
        // 原注册资本比例信息
        $registeredCapitalRatioArr = [];

        // 原股东姓名数组
        $nameOfOriginalShareholder = [];

        // 住所（经营场所）申报承诺表
        $declarationOfCommitmentForm = [];

        // 判断需要哪个章程 自然人投资或控股章程0    自然人独资章程1    公司独资章程2
        $constitution = $this->selectConstitution($info);

        foreach ($info['partners'] as $k1 => &$v1) {
            $shareholderRowArr[]['shareholderContent'] = '股东：' . $v1->name;

            if (count($info['partners']) == 1) {
                $basicTypeArr['shareholder'] .= '股东' . $v1->name;
                $basicTypeArr['shareholderOld'] .= '股东' . $v1->name;
            } elseif (count($info['partners']) == 2) {
                if ($k1 == (count($info['partners']) - 1)) {
                    $basicTypeArr['shareholder'] .= '股东' . $v1->name;
                    $basicTypeArr['shareholderOld'] .= '股东' . $v1->name;
                } else {
                    $basicTypeArr['shareholder'] .= '股东' . $v1->name . '和';
                    $basicTypeArr['shareholderOld'] .= '股东' . $v1->name . '和';
                }
            } else {
                if ($k1 == (count($info['partners']) - 1)) {
                    $basicTypeArr['shareholder'] .= '股东' . $v1->name;
                    $basicTypeArr['shareholderOld'] .= '股东' . $v1->name;
                } else if ($k1 == 0) {
                    $basicTypeArr['shareholder'] .= '股东' . $v1->name . '和';
                    $basicTypeArr['shareholderOld'] .= '股东' . $v1->name . '和';
                } else {
                    $basicTypeArr['shareholder'] .= '股东' . $v1->name . '、';
                    $basicTypeArr['shareholderOld'] .= '股东' . $v1->name . '、';
                }
            }

            $rules_shareholder_arr[$k1]['rules_shareholder_content'] = "股东：{$v1->name}";
            $v1->ratio = str_replace(' 万人民币', '', $v1->should_capi_items[0]->shoud_capi) * 100 / $info['regist_capi_new'] . '%';

            $registeredCapitalRatioArr[$v1->name] = $v1->ratio;

            $nameOfOriginalShareholder[] = $v1->name;
        }
        unset($v1);

        // 原股东人数
        $numberOfOriginalShareholders = count($info['partners']);

        foreach ($postData['changCategory'] as $v) {
            // 变更名称
            $changeCategoryName = db('change_category')
                ->where("id={$v['id']}")
                ->value('name');

            if ($changeCategoryName == '公司名称') {
                if (empty($v['value']) || $info['name'] == $v['value']) {
                    $this->setError('公司名称填写错误或无变更');
                    return false;
                }

                /*--------公司登记（备案）申请书 变更事项--------*/
                $changeTypeArr[] = [
                    'changeType' => '名称',
                    'changeOld' => $info['name'],
                    'changeNew' => $v['value']
                ];

                /*--------股东会决议内容--------*/
                $commentRowArr = [
                    ['comentContent' => "公司名称变更为：{$v['value']}。"],
                    ['comentContent' => "公司经营管理机构不变。"],
                    ['comentContent' => "重新制定公司章程。"]
                ];

                /*--------选择公司章程--------*/
                $changeFunction['documentStrArr'] = $this->selectDocumentStrArr($constitution, $changeFunction['documentStrArr']);

                /*--------公司章程中内容--------*/
                $oldTerm = diffDate(date('Y-m-d', strtotime($info['term_start']) - 3600 * 24), $info['term_end']);
                $basicTypeArr['${rules_company_name}'] = $v['value'];
                $basicTypeArr['${rules_company_address}'] = $info['addresses'];
                $basicTypeArr['${rules_company_business_scope}'] = $info['scope'];
                $basicTypeArr['${rules_company_regist_capital}'] = $info['regist_capi_new'];
                $basicTypeArr['${rules_business_term}'] = $oldTerm['year'];
                foreach ($info['partners'] as $v2) {
                    $rules_shareholder_row_arr[] = [
                        'rules_shareholder_people' => $v2->name,
                        'rules_money' => $v2->should_capi_items[0]->shoud_capi,
                        'rules_ratio' => $v2->ratio,
                        'rules_method' => "以{$v2->should_capi_items[0]->invest_type}出资",
                        'rules_time' => $v2->should_capi_items[0]->should_capi_date,
                    ];
                }
            } elseif ($changeCategoryName == '经营场所') {
                if (empty($v['value']) || $info['addresses'] == $v['value'] || !isset($v['area']) || empty($v['area']) || !isset($v['isFilingAddress'])) {
                    $this->setError('经营场所信息填写错误或无变更');
                    return false;
                }
                // 是否有地址备案 0否 1是
                $isFilingAddressArr = [0, 1];
                if (isset($v['isFilingAddress']) && !in_array($v['isFilingAddress'], $isFilingAddressArr)) {
                    $this->setError('是否有备案地址参数只能是0和1');
                    return false;
                }
                $isFilingAddressText = $v['isFilingAddress'] ? '变更为' : '备案为';

                /*--------公司登记（备案）申请书 变更事项--------*/
                $recordTypeArr[] = [
                    'reocrdType' => $changeCategoryName,
                    'recordOld' => $v['isFilingAddress'] ? $info['addresses'] : '',
                    'recordNew' => $v['value']
                ];

                /*--------经营场所承诺书--------*/
                $basicTypeArr['${businessAddress}'] = $v['value'];
                $basicTypeArr['${area}'] = $v['area'];

                /*--------股东会决议内容--------*/
                $commentRowArr = array(
                    array('comentContent' => "公司经营场所{$isFilingAddressText}：" . $v['value'] . "。"),
                );

                /*--------住所（经营场所）申报承诺表--------*/
                $declarationOfCommitmentForm['companyName'] = $info['name'];
                $declarationOfCommitmentForm['companyAddress'] = '';
                $declarationOfCommitmentForm['area'] = '';
                $declarationOfCommitmentForm['houseOwnerUsername'] = '';
                $declarationOfCommitmentForm['houseOwnerMobile'] = '';
                $declarationOfCommitmentForm['companyAddress_1'] = $v['value'];
                $declarationOfCommitmentForm['area_1'] = $v['area'];
                $declarationOfCommitmentForm['houseOwnerUsername_1'] = isset($v['houseOwnerUsername']) ? $v['houseOwnerUsername'] : '';
                $declarationOfCommitmentForm['houseOwnerMobile_1'] = isset($v['houseOwnerMobile']) ? $v['houseOwnerMobile'] : '';

                /*--------章程修正案--------*/
                /*$descRowArr = [
                    [
                        'descTitle' => "原公司章程第三条：“公司经营场所：{$info['addresses']}。”。",
                        'descContent' => "现修正为：“公司经营场所：{$v['value']}。”。",
                    ],
                ];*/

                // $isZhangcheng = 1;

            } elseif ($changeCategoryName == '公司住所') {
                if (empty($v['value']) || empty($v['area']) || $info['addresses'] == $v['value']) {
                    $this->setError('变更资料填写错误或无变更');
                    return false;
                }

                /*--------公司登记（备案）申请书 变更事项--------*/
                $changeTypeArr[] = [
                    'changeType' => '住所',
                    'changeOld' => $info['addresses'],
                    'changeNew' => $v['value']
                ];

                /*--------股东会决议内容--------*/
                $commentRowArr = [
                    ['comentContent' => "公司住所变更为：" . $v['value'] . "。"]
                ];

                /*--------章程修正案--------*/
                $descRowArr = [
                    [
                        'descTitle' => "原公司章程第二条：“公司住所：{$info['addresses']}。”。",
                        'descContent' => "现修正为：“公司住所：{$v['value']}。”。",
                    ],
                ];

                /*--------住所（经营场所）申报承诺表--------*/
                $declarationOfCommitmentForm['companyName'] = $info['name'];
                $declarationOfCommitmentForm['companyAddress'] = $v['value'];
                $declarationOfCommitmentForm['area'] = $v['area'];
                $declarationOfCommitmentForm['houseOwnerUsername'] = isset($v['houseOwnerUsername']) ? $v['houseOwnerUsername'] : '';
                $declarationOfCommitmentForm['houseOwnerMobile'] = isset($v['houseOwnerMobile']) ? $v['houseOwnerMobile'] : '';
                $declarationOfCommitmentForm['companyAddress_1'] = '';
                $declarationOfCommitmentForm['area_1'] = '';
                $declarationOfCommitmentForm['houseOwnerUsername_1'] = '';
                $declarationOfCommitmentForm['houseOwnerMobile_1'] = '';

                $isZhangcheng = 1;
            } elseif ($changeCategoryName == '经营范围') {
                if (empty($v['value']) || $info['scope'] == $v['value']) {
                    $this->setError('经营范围填写错误或无变更');
                    return false;
                }

                // 匹配到)并且后面是数字
                if (strripos($v['value'], ')')) {
                    if (is_numeric(substr($v['value'], strripos($v['value'], ')') + 1, 4))) {
                        $v['value'] = substr($v['value'], 0, strripos($v['value'], ')') + 1);
                    }
                }

                /*--------公司登记（备案）申请书 变更事项--------*/
                $recordTypeArr[] = [
                    'reocrdType' => $changeCategoryName,
                    'recordOld' => $info['scope'],
                    'recordNew' => $v['value']
                ];

                /*--------股东会决议内容--------*/
                $commentRowArr = [
                    ['comentContent' => "公司经营范围变更为：{$v['value']}"]
                ];
                $basicTypeArr['${belongOrg}'] = $info['belong_org'];

                /*--------章程修正案--------*/
                $descRowArr = [
                    [
                        'descTitle' => "原公司章程第四条：“公司经营范围：{$info['scope']}”。",
                        'descContent' => "现修正为：“公司经营范围：{$v['value']}。”。",
                    ],
                ];

                $isZhangcheng = 1;

            } elseif ($changeCategoryName == '营业期限') {
                $oldTerm = diffDate(date('Y-m-d', strtotime($info['term_start']) - 3600 * 24), $info['term_end']);
                if (empty($v['value']) || $oldTerm == $v['value']) {
                    $this->setError('营业期限填写错误或无变更');
                    return false;
                }

                /*--------公司登记（备案）申请书 变更事项--------*/
                $recordTypeArr[] = [
                    'reocrdType' => $changeCategoryName,
                    'recordOld' => $oldTerm['year'] . '年',
                    'recordNew' => $v['value'] . '年'
                ];


                /*--------股东会决议内容--------*/
                $commentRowArr = [
                    ['comentContent' => "公司经营期限变更为：{$v['value']}年。"]
                ];

                /*--------章程修正案--------*/
                $howManyArticles = '';
                if($isDecision)
                {
                    // 多个股东 投资或控股
                    $howManyArticles = '四十一条';
                }
                else
                {
                    // 根据股东名称字数判断是自然人独资或公司独资
                    $howManyArticles = mb_strlen($info['partners'][0]->name, 'UTF-8')>5 ? '三十三条' : '三十四条';
                }

                $descRowArr = [
                    [
                        'descTitle' => "原公司章程第{$howManyArticles}：“公司的营业期限为{$oldTerm['year']}年。”。",
                        'descContent' => "现修正为：“公司的营业期限为{$v['value']}年”。",
                    ],
                ];

                $isZhangcheng = 1;

            } elseif ($changeCategoryName == '出资时间') {
                if (empty($v['value']) || $info['partners'][0]->should_capi_items[0]->should_capi_date == $v['value'] || date('Y-m-d', strtotime($v['value'])) == '1970-01-01') {
                    $this->setError('认缴出资日期填写错误或无变更');
                    return false;
                }

                /*--------公司登记（备案）申请书 变更事项--------*/
                $recordTypeArr[] = [
                    'reocrdType' => $changeCategoryName,
                    'recordOld' => $info['partners'][0]->should_capi_items[0]->should_capi_date . '前',
                    'recordNew' => $v['value'] . '前'
                ];

                /*--------股东会决议内容--------*/
                $commentRowArr = [
                    ['comentContent' => "公司出资时间变更为：于{$v['value']}前。"],
                    ['comentContent' => "重新制定公司章程。"]
                ];

                /*--------选择公司章程--------*/
                $changeFunction['documentStrArr'] = $this->selectDocumentStrArr($constitution, $changeFunction['documentStrArr']);

                /*--------公司章程中内容--------*/
                $oldTerm = diffDate(date('Y-m-d', strtotime($info['term_start']) - 3600 * 24), $info['term_end']);
                $basicTypeArr['${rules_company_name}'] = $info['name'];
                $basicTypeArr['${rules_company_address}'] = $info['addresses'];
                $basicTypeArr['${rules_company_business_scope}'] = $info['scope'];
                $basicTypeArr['${rules_company_regist_capital}'] = $info['regist_capi_new'];
                $basicTypeArr['${rules_business_term}'] = $oldTerm['year'];
                foreach ($info['partners'] as $k1 => &$v1) {
                    $v1->should_capi_items[0]->should_capi_date = $v['value'];
                    $rules_shareholder_row_arr[] = [
                        'rules_shareholder_people' => $v1->name,
                        'rules_money' => $v1->should_capi_items[0]->shoud_capi,
                        'rules_ratio' => $v1->ratio,
                        'rules_method' => "以{$v1->should_capi_items[0]->invest_type}出资",
                        'rules_time' => $v1->should_capi_items[0]->should_capi_date,
                    ];
                }
                unset($v1);

            } elseif ($changeCategoryName == '法定代表人') {
                if (empty($v['value']) || $info['oper_name'] == $v['value'] || !isset($v['legal_card']) || empty($v['legal_card']) || !isset($v['legal_address']) || empty($v['legal_address']) || !isset($v['isManager'])) {
                    $this->setError('法定代表人信息填写错误或无变更');
                    return false;
                }

                /*--------公司登记（备案）申请书 变更事项--------*/
                $changeTypeArr[] = [
                    'changeType' => $changeCategoryName,
                    'changeOld' => $info['oper_name'],
                    'changeNew' => $v['value']
                ];

                /*--------股东会决议内容--------*/
                if (!empty($v['isManager'])) {
                    // 勾选同时担任经理 此时需要判断变更后的那个人是否是监事，如果是监事，不能勾选
                    if ($v['value'] == $supervisor['name']) {
                        $this->setError('变更后的股东已是监事，不能同时担任经理');
                        return false;
                    }
                    $commentRowArr = [
                        ['comentContent' => "免去{$info['oper_name']}的公司执行董事职务，选举{$v['value']}为公司执行董事。"],
                        ['comentContent' => "免去{$info['oper_name']}的公司经理职务，选举{$v['value']}为公司经理。"],
                        ['comentContent' => "继续聘任{$supervisor['name']}为公司监事。"]
                    ];
                } else {
                    $commentRowArr = [
                        ['comentContent' => "免去{$info['oper_name']}的公司执行董事职务，选举{$v['value']}为公司执行董事。"],
                        ['comentContent' => "继续聘任{$manager['name']}为公司经理。"],
                        ['comentContent' => "继续聘任{$supervisor['name']}为公司监事。"]
                    ];
                }

                /*--------法定代表人信息--------*/
                $basicTypeArr['legal_name'] = $v['value'];
                $basicTypeArr['legal_method'] = $generationMode;
                $basicTypeArr['legal_card'] = $v['legal_card'];
                $basicTypeArr['legal_address'] = $v['legal_address'];

                /*--------董事_监事_经理信息--------*/
                $position_director_arr = [
                    [
                        'position_director_people' => $v['value'],
                        'position_director_card' => $v['legal_card'],
                        'position_director_name' => '执行董事',
                        'position_director_method' => $generationMode,
                    ],
                ];
            } elseif ($changeCategoryName == '监事') {
                /*--------旧监事信息--------*/
                $supervisor = [];
                foreach ($info['employees'] as $v1) {
                    if ($v1['job_title'] == '监事') {
                        $supervisor = $v1;
                        break;
                    }
                }

                if (empty($v['value']) || $supervisor['name'] == $v['value'] || !isset($v['legal_card']) || empty($v['legal_card'])) {
                    $this->setError('监事信息填写错误或无变更');
                    return false;
                }

                /*--------股东会决议具体内容--------*/
                $commentRowArr = [
                    ['comentContent' => "继续选举{$info['oper_name']}为公司执行董事。"],
                    ['comentContent' => "继续聘任{$info['oper_name']}为公司经理。"],
                    ['comentContent' => "免去{$supervisor['name']}的公司监事职务，选举{$v['value']}为公司监事。"],
                ];

                /*--------董事_监事_经理信息--------*/
                $position_director_arr = [
                    [
                        'position_director_people' => $v['value'],
                        'position_director_card' => $v['legal_card'],
                        'position_director_name' => '监事',
                        'position_director_method' => $generationMode,
                    ],
                ];
            } elseif ($changeCategoryName == '注册资本') {
                $v['value'] = 0;
                if (count($v['info']) != count($info['partners'])) {
                    $this->setError('注册资本信息和股东信息没有对应上');
                    return false;
                }

                // 股东名称数组
                $partnersNameArr = array_column($info['partners'], 'name');
                foreach ($v['info'] as $v3) {
                    $v['value'] += $v3['money'];

                    // 是否有对应股东
                    if (!in_array($v3['name'], $partnersNameArr)) {
                        $this->setError('注册资本信息和股东信息没有对应上');
                        return false;
                    }
                }

                if (empty($v['value']) || $v['value'] == $info['regist_capi_new']) {
                    $this->setError('注册资本填写错误或无变更');
                    return false;
                }

                /*--------公司登记（备案）申请书 变更事项--------*/
                $changeTypeArr[] = [
                    'changeType' => $changeCategoryName,
                    'changeOld' => $info['regist_capi_new'] . ' 万元人民币',
                    'changeNew' => $v['value'] . ' 万元人民币'
                ];

                /*--------选择公司章程--------*/
                $changeFunction['documentStrArr'] = $this->selectDocumentStrArr($constitution, $changeFunction['documentStrArr']);

                /*--------股东会决议具体内容--------*/
                if ($v['value'] >= $info['regist_capi_new']) {
                    foreach ($changeFunction['documentStrArr'] as $k2 => $v2) {
                        if ($v2['template']['name'] == '公司债务清偿或担保情况说明') unset($changeFunction['documentStrArr'][$k2]);
                    }
                    // 增资
                    $comentContent = "公司注册资本由{$info['regist_capi_new']}万元增加至{$v['value']}万元。公司增资后，各股东的出资情况如下：<w:br />";
                } else {
                    // 减资
                    $comentContent = "公司减少注册资本，符合《中华人民共和国公司法》规定的程序，公司此次减资已依法通知或公告所有债权人并取得所有债权人的同意。
                    <w:br />公司注册资本由{$info['regist_capi_new']}万元增加至{$v['value']}万元。公司增资后，各股东的出资情况如下：<w:br />";
                }
                if (!isset($v['info']) || empty($v['info']) || count($v['info']) != count($info['partners'])) {
                    $this->setError('注册资本信息填写错误或无变更');
                    return false;
                }
                foreach ($v['info'] as $v2) {
                    if (!isset($v2['name']) || empty($v2['name']) || !isset($v2['money']) || empty($v2['money']) || !isset($v2['time']) || empty($v2['time']) || !isset($v2['card']) || empty($v2['card']) || !isset($v2['mode']) || empty($v2['mode'])) {
                        $this->setError('注册资本信息填写错误或无变更');
                        return false;
                    }

                    // 比例
                    $proportion = round($v2['money'] * 100 / $v['value'], 2);

                    // 注册资本比例校验
                    if ($proportion . '%' != $registeredCapitalRatioArr[$v2['name']]) {
                        $this->setError('注册资本比例错误');
                        return false;
                    }

                    $time = date('Y年m月d日', strtotime($v2['time']));
                    $comentContent .= "　　　　股东{$v2['name']}持有公司{$proportion}%的股权（认缴注册资本{$v2['money']}万元）,以{$v2['mode']}形式出资,于{$time}前缴足；<w:br />";

                    // 出资情况
                    $contributionArr[] = [
                        'capital_name' => $v2['name'],
                        'capital_card' => $v2['card'],
                        'capital_money' => $v2['money'],
                        'capital_time' => $time . '前',
                        'capital_ratio' => $proportion . '%',
                    ];

                    /*--------公司章程中内容--------*/
                    $rules_shareholder_row_arr[] = [
                        'rules_shareholder_people' => $v2['name'],
                        'rules_money' => $v2['money'] . '万元',
                        'rules_ratio' => $proportion . '%',
                        'rules_method' => "以{$v2['mode']}出资",
                        'rules_time' => $time,
                    ];
                }
                if ($v['value'] >= $info['regist_capi_new']) {
                    $comentContent .= "　　　　股东承诺将按原认缴出资额承担相应法律责任。<w:br />";
                } else {
                    $comentContent .= "对于公司减资前存在的债务，在公司减资后，如公司资产不足以清偿，全体股东承诺将按原认缴出资额承担相应法律责任。<w:br />";
                }
                $commentRowArr = [
                    ['comentContent' => $comentContent],
                    ['comentContent' => "重新制定公司章程。"]
                ];

                /*--------公司章程中内容--------*/
                $oldTerm = diffDate(date('Y-m-d', strtotime($info['term_start']) - 3600 * 24), $info['term_end']);
                $basicTypeArr['${rules_company_name}'] = $info['name'];
                $basicTypeArr['${rules_company_address}'] = $info['addresses'];
                $basicTypeArr['${rules_company_business_scope}'] = $info['scope'];
                $basicTypeArr['${rules_company_regist_capital}'] = $v['value'];
                $basicTypeArr['${rules_business_term}'] = $oldTerm['year'];

            } elseif ($changeCategoryName == '股东') {
                /*-----------------校验数据合法性 start-----------------*/
                // 1须有变更数据 2变更数据不能为空 3变更前后人名不能相同 4一个人不能变更两次
                if (empty($v['info'])) {
                    $this->setError('请填写变更数据');
                    return false;
                }
                if (empty($v['legal_name']) || empty($v['legal_card']) || empty($v['legal_address'])) {
                    $this->setError('请填写法人信息');
                    return false;
                }
                if (empty($v['contact_name']) || empty($v['contact_card']) || empty($v['contact_address'])) {
                    $this->setError('请填写联络人信息');
                    return false;
                }

                $nameArr = array_column($v['info'], 'oldName');
                if (count($nameArr) != count(array_unique($nameArr))) $this->setError('一个股东不能变更多次');
                // 转让后的字符串
                $afterTransfer = '';

                // 是否同时变更法人
                $isChangeLegal = 0;

                foreach ($v['info'] as $k => $v1) {
                    if (!in_array($v1['oldName'], array_column($info['partners'], 'name'))) {
                        $this->setError('不存在该股东');
                        return false;
                    }
                    if (empty($v1['oldName']) || empty($v1['changeName']) || empty($v1['oldLegalCard']) || empty($v1['oldAddress']) || empty($v1['changeLegalCard'])
                        || empty($v1['changeAddress']) || !isset($v1['position']) || empty($v1['ratio']) || empty($v1['time'])) {
                        $this->setError('变更数据不完整');
                        return false;
                    }
                    if ($v1['oldName'] == $v1['changeName']) {
                        $this->setError('变更前后人名不能相同');
                        return false;
                    }

                    // 如果有变更法人那么此时所填写的法人信息一定是新的法人信息
                    if ($v1['position'] == '法人') {
                        if ($v['legal_name'] != $v1['changeName']) {
                            $this->setError('同时变更为法人时，必须填写新的法人信息');
                            return false;
                        }

                        $isChangeLegal = 1;
                    }

                    $v1['ratio'] .= '%';

                    /*-----------------董事、监事、经理信息文档数据 start----------------*/
                    $position_director_arr[$k] = [
                        'position_director_people' => $v1['changeName'],
                        'position_director_card' => $v1['changeLegalCard'],
                        'position_director_name' => $v1['position'],
                        'position_director_method' => $generationMode,
                    ];
                    /*-----------------董事、监事、经理信息文档数据 stop----------------*/

                    /*-----------------股东或股东会决议内容 start----------------*/
                    // 原股东信息
                    $oldPartners = [];

                    // 是否是股东内部转让 0是 1否
                    $isInternalTransfer = 0;

                    foreach ($info['partners'] as $k2 => $v2) {
                        // 找到原股东
                        if ($v1['oldName'] == $v2->name) {
                            // 身份证号同步到股东数据中
                            $info['partners'][$k2]->changeLegalCard = $v1['oldLegalCard'];
                            $info['partners'][$k2]->time = $v2->should_capi_items[0]->should_capi_date;

                            // 原股东股份比例和变更的股份比例相同
                            if ($v2->ratio == $v1['ratio']) {
                                // 查询changeName是否是其中的一个股东
                                $changeKey = -1;
                                foreach ($info['partners'] as $k3 => $v3) {
                                    if ($v3->name == $v1['changeName']) {
                                        $changeKey = $k3;
                                        break;
                                    }
                                }
                                if ($changeKey != -1) {
                                    $info['partners'][$changeKey]->should_capi_items[0]->should_capi_date = $v1['time'];
                                    $info['partners'][$changeKey]->ratio = (floatval(str_replace('%', '', $info['partners'][$changeKey]->ratio)) + floatval(str_replace('%', '', $v1['ratio']))) . '%';
                                    $info['partners'][$changeKey]->time = $v1['time'];
                                    $info['partners'][$changeKey]->changeLegalCard = $v1['changeLegalCard'];
                                    unset($info['partners'][$k2]);
                                } else {
                                    // 比例直接替换股东数据
                                    $v2->name = $v1['changeName'];
                                    $v2->ratio = $v1['ratio'];
                                    $v2->time = $v1['time'];
                                    $v2->changeLegalCard = $v1['changeLegalCard'];

                                    $isInternalTransfer = 1;
                                }
                            } else {
                                // 原股东股份比例和变更的股份比例相同

                                // 查询变更后的股东是否是该公司原股东
                                $changeKey = -1;
                                foreach ($info['partners'] as $k3 => $v3) {
                                    if ($v3->name == $v1['changeName']) {
                                        $changeKey = $k3;
                                        break;
                                    }
                                }

                                if ($changeKey != -1) {
                                    // 是公司原股东 修改股东出资时间、出资比例、身份证号
                                    $info['partners'][$changeKey]->should_capi_items[0]->should_capi_date = $v1['time'];
                                    $info['partners'][$changeKey]->ratio = (floatval(str_replace('%', '', $info['partners'][$changeKey]->ratio)) + floatval(str_replace('%', '', $v1['ratio']))) . '%';
                                    $info['partners'][$changeKey]->time = $v1['time'];
                                    $info['partners'][$changeKey]->changeLegalCard = $v1['changeLegalCard'];
                                } else {
                                    // 不是公司原股东 新增股东信息
                                    $v3 = json_decode(json_encode($v2), true);
                                    $v3['name'] = $v1['changeName'];
                                    $v3['should_capi_items'][0]['should_capi_date'] = $v1['time'];
                                    $v3['ratio'] = $v1['ratio'];
                                    $v3['time'] = $v1['time'];
                                    $v3['changeLegalCard'] = $v1['changeLegalCard'];
                                    $info['partners'][] = json_decode(json_encode($v3));

                                    $isInternalTransfer = 1;
                                }
                                // 比例不相同，旧的比例减去减少的比例
                                if (floatval(str_replace('%', '', $v2->ratio)) - floatval(str_replace('%', '', $v1['ratio'])) <= 0) {
                                    $this->setError('股份比例错误');
                                    return false;
                                }
                                $info['partners'][$k2]->ratio = (floatval(str_replace('%', '', $v2->ratio)) - floatval(str_replace('%', '', $v1['ratio']))) . '%';
                            }

                            $oldPartners['shoud_capi'] = (round($info['regist_capi_new'] * floatval(str_replace('%', '', $v1['ratio'])) / 100, 2)) . '万元';
                            $oldPartners['perShare'] = str_replace(' 元', '', $oldPartners['shoud_capi']);

                            break;
                        }
                    }

                    $commentRowArr[] = ['comentContent' => "股东{$v1['oldName']}将所持有的占公司{$v1['ratio']}的股权（认缴注册资本{$oldPartners['shoud_capi']}），以{$oldPartners['perShare']}的价格转让给{$v1['changeName']}。"];
                    if (!empty($v1['position'])) {
                        if ($v1['position'] == '监事') {
                            $v1['position'] = '公司监事';
                        }
                        $commentRowArr_1[] = ['comentContent' => "选举{$v1['changeName']}为{$v1['position']}。"];
                    }
                    /*-----------------股东或股东会决议内容 stop----------------*/

                    /*-----------------股权转让协议 ----------------*/
                    $equity_transfer_arr[$k]['company_name'] = $info['name'];
                    $equity_transfer_arr[$k]['oldName'] = $v1['oldName'];
                    $equity_transfer_arr[$k]['oldLegalCard'] = $v1['oldLegalCard'];
                    $equity_transfer_arr[$k]['oldAddress'] = $v1['oldAddress'];
                    $equity_transfer_arr[$k]['stockRight'] = $v1['ratio'];
                    $equity_transfer_arr[$k]['oldRegistered'] = (round($info['regist_capi_new'] * floatval(str_replace('%', '', $v1['ratio'])) / 100, 2)) . '万元';
                    $equity_transfer_arr[$k]['oldPrice'] = round($info['regist_capi_new'] * floatval(str_replace('%', '', $v1['ratio'])) / 100, 2) . '元';
                    $equity_transfer_arr[$k]['changeName'] = $v1['changeName'];
                    $equity_transfer_arr[$k]['changeLegalCard'] = $v1['changeLegalCard'];
                    $equity_transfer_arr[$k]['changeAddress'] = $v1['changeAddress'];
                    $equity_transfer_arr[$k]['changePrice'] = round($info['regist_capi_new'] * floatval(str_replace('%', '', $v1['ratio'])) / 100, 2);
                    $equity_transfer_arr[$k]['registered'] = $info['regist_capi_new'] . '万元';
                }
                sort($info['partners']);

                /*-----------------股权转让协议 ----------------*/
                if(count($equity_transfer_arr) > 1 )
                {
                    // 找出股权转让协议模板信息以及key
                    $oldEquityTransferTemplate = [];
                    foreach ($changeFunction['documentStrArr'] as $k3 => $v3) {
                        if ($v3['template']['name'] == '股权转让协议') {
                            $oldEquityTransferTemplate = $v3;
                            break;
                        }
                    }
                    $basicTemplate = db('template')
                        ->where("name='股权转让协议'")
                        ->field('id')
                        ->find();
                    $basicTemplate['template'] = db('template')
                        ->where("id={$basicTemplate['id']}")
                        ->field('id, name, src')
                        ->find();
                    foreach ($equity_transfer_arr as $k3=>$v3)
                    {
                        if($k3 == 0) continue;

                        $basicTemplate['template']['name'] = '股权转让协议第'.($k3).'份';
                        $basicTemplate['sort'] = $oldEquityTransferTemplate['sort'];
                        // 将第二个股东决定或者股东会决议插入进去
                        $changeFunction['documentStrArr'][] = $basicTemplate;
                    }
                    sort($changeFunction['documentStrArr']);
                }

                // 没有变更法人 那么法人信息应该和原来的法人信息一致
                if (empty($isChangeLegal) && $v['legal_name'] != $info['oper_name']) {
                    $this->setError('法人信息错误');
                    return false;
                }

                // 变更股东数组
                $changeNameArr = array_column($v['info'], 'changeName');
                /*-----------------校验数据合法性 stop-----------------*/

                /*-----------------法定代表人信息文档数据 start----------------*/
                $basicTypeArr['legal_name'] = $v['legal_name'];
                $basicTypeArr['legal_method'] = $generationMode;
                $basicTypeArr['legal_card'] = $v['legal_card'];
                $basicTypeArr['legal_address'] = $v['legal_address'];
                /*-----------------法定代表人信息文档数据 stop----------------*/

                /*--------选择公司章程--------*/
                $changeFunction['documentStrArr'] = $this->selectDocumentStrArr($constitution, $changeFunction['documentStrArr']);

                /*-----------------公司章程 start----------------*/
                $oldTerm = diffDate(date('Y-m-d', strtotime($info['term_start']) - 3600 * 24), $info['term_end']);
                $basicTypeArr['${rules_company_name}'] = $info['name'];
                $basicTypeArr['${rules_company_address}'] = $info['addresses'];
                $basicTypeArr['${rules_company_business_scope}'] = $info['scope'];
                $basicTypeArr['${rules_company_regist_capital}'] = $info['regist_capi_new'];
                $basicTypeArr['${rules_business_term}'] = $oldTerm['year'];
                $rules_shareholder_arr = [];

                // 变更后股东姓名数组
                $nameOfShareholderAfterChange = [];
                foreach ($info['partners'] as $v2) {
                    $rules_shareholder_row_arr[] = [
                        'rules_shareholder_people' => $v2->name,
                        'rules_money' => (round($info['regist_capi_new'] * floatval(str_replace('%', '', $v2->ratio)) / 100, 2)) . '万人民币',
                        'rules_ratio' => $v2->ratio,
                        'rules_method' => "以{$v2->should_capi_items[0]->invest_type}出资",
                        'rules_time' => $v2->should_capi_items[0]->should_capi_date,
                    ];

                    $rules_shareholder_arr[]['rules_shareholder_content'] = "股东：{$v2->name}";

                    $shoud_capi = (round($info['regist_capi_new'] * floatval(str_replace('%', '', $v2->ratio)) / 100, 2)) . '万元';

                    if (empty($afterTransfer)) {
                        $afterTransfer .= "股权转让后，{$v2->name}持有公司{$v2->ratio}的股权（认缴注册资本{$shoud_capi}）。";
                    } else {
                        $afterTransfer .= "{$v2->name}持有公司{$v2->ratio}的股权（认缴注册资本{$shoud_capi}）。";
                    }

                    /*-----------------出资情况----------------*/
                    $contributionArr[] = [
                        'capital_name' => $v2->name,
                        'capital_card' => $v2->changeLegalCard,
                        'capital_money' => $shoud_capi,
                        'capital_time' => $v2->time,
                        'capital_ratio' => $v2->ratio,
                    ];

                    $nameOfShareholderAfterChange[] = $v2->name;

                    $shareholderRowArr_1[]['shareholderContent'] = '股东：' . $v2->name;

                    if (count($info['partners']) == 1) {
                        $basicTypeArr['shareholder_1'] .= '股东' . $v2->name;
                    } elseif (count($info['partners']) == 2) {
                        if ($k1 == (count($info['partners']) - 1)) {
                            $basicTypeArr['shareholder_1'] .= '股东' . $v2->name;
                        } else {
                            $basicTypeArr['shareholder_1'] .= '股东' . $v2->name . '和';
                        }
                    } else {
                        if ($k1 == (count($info['partners']) - 1)) {
                            $basicTypeArr['shareholder_1'] .= '股东' . $v2->name;
                        } else if ($k1 == 0) {
                            $basicTypeArr['shareholder_1'] .= '股东' . $v2->name . '和';
                        } else {
                            $basicTypeArr['shareholder_1'] .= '股东' . $v2->name . '、';
                        }
                    }

                }
                $commentRowArr[] = ['comentContent' => $afterTransfer];
                if (empty($commentRowArr_1)) {
                    $commentRowArr_1[] = ['comentContent' => "其它管理机构不变。"];
                }
                $commentRowArr_1[] = ['comentContent' => "重新制定公司章程。"];
                /*-----------------公司章程 stop----------------*/

                /*-----------------公司登记文档数据-----------------*/
                // 现股东人数
                $numberOfCurrentShareholders = count($info['partners']);

                // 股权内部转让
                $changeOld = '';
                $changeNew = '';
                if (empty($isInternalTransfer) && $numberOfCurrentShareholders == $numberOfOriginalShareholders) {
                    $changeCategoryName = '';
                } else {
                    $changeOld = implode(',', $nameOfOriginalShareholder);
                    $changeNew = implode(',', $nameOfShareholderAfterChange);
                }

                $changeTypeArr[$k] = [
                    'changeType' => $changeCategoryName,
                    'changeOld' => $changeOld,
                    'changeNew' => $changeNew
                ];

                /*-----------------联系人信息 start----------------*/
                $basicTypeArr['${contact_name}'] = $v['contact_name'];
                $basicTypeArr['${contact_card}'] = $v['contact_card'];
                $basicTypeArr['${contact_address}'] = $v['contact_address'];
                $basicTypeArr['${contact_mobile}'] = '';
                /*-----------------联系人信息 stop----------------*/

                /*-----------------年报承诺书 start----------------*/
                $basicTypeArr['${company_name}'] = $info['name'];
                /*-----------------年报承诺书 stop----------------*/

                /*-----------------根据变更后的股东信息判断是股东决定还是股东会决议----------------*/
                // 找出上一个股东会决议或股东会决定的key以及相关信息
                foreach ($changeFunction['documentStrArr'] as $k3 => $v3) {
                    if ($v3['template']['name'] == '股东会决议' || $v3['template']['name'] == '股东决定') {
                        $oldBasicTemplate = $v3;
                        $oldBasicTemplate['key'] = $k3;
                        break;
                    }
                }

                // 为true时是股东会决议，股东会决议保留，删除股东决定
                $isChangeDecision = $this->isDecision($info);
                $basicTemplateKey = $oldBasicTemplate['template']['name'] == '股东会决议' ? $oldBasicTemplate['key'] + 1 : $oldBasicTemplate['key'] - 1;
                if ($isChangeDecision) {
                    // 此时新增一个股东会决议模板
                    $basicTemplate = db('template')
                        ->where("name='股东会决议'")
                        ->field('id')
                        ->find();
                    $basicTemplate['template'] = db('template')
                        ->where("id={$basicTemplate['id']}")
                        ->field('id, name, src')
                        ->find();
                    $basicTemplate['template']['name'] = '股东会决议第二份';
                } else {
                    // 此时新增一个股东决定模板
                    $basicTemplate = db('template')
                        ->where("name='股东决定'")
                        ->field('id')
                        ->find();
                    $basicTemplate['template'] = db('template')
                        ->where("id={$basicTemplate['id']}")
                        ->field('id, name, src')
                        ->find();
                    $basicTemplate['template']['name'] = '股东决定第二份';
                }
                $basicTemplate['sort'] = $oldBasicTemplate['sort'];
                // 将第二个股东决定或者股东会决议插入进去
                $changeFunction['documentStrArr'][$basicTemplateKey] = $basicTemplate;
                sort($changeFunction['documentStrArr']);


                /*-----------------处理公司登记文档数据----------------*/
                $changeTypeArr_1 = $changeTypeArr;
                if (count($changeTypeArr_1) > 1) {
                    for ($i = 0; $i < count($changeTypeArr_1); $i++) {
                        for ($j = $i + 1; $j < count($changeTypeArr_1); $j++) {
                            if ($changeTypeArr_1[$i]['changeOld'] == $changeTypeArr_1[$j]['changeOld']) {
                                $changeTypeArr_1[$i]['changeNew'] = $changeTypeArr_1[$i]['changeNew'] . ',' . $changeTypeArr_1[$j]['changeNew'];
                                unset($changeTypeArr_1[$j]);
                            }
                        }
                    }
                }
                sort($changeTypeArr_1);
                $changeTypeArr = $changeTypeArr_1;

            } elseif ($changeCategoryName == '联络人') {
                if (!isset($v['contact_name']) || empty($v['contact_name']) || !isset($v['contact_card']) || empty($v['contact_card'])
                    || !isset($v['contact_address']) || empty($v['contact_address'])|| !isset($v['contact_mobile']) || empty($v['contact_mobile'])) {
                    $this->setError('联络人信息填写错误');
                    return false;
                }

                /*-----------------联系人信息 start----------------*/
                $basicTypeArr['${contact_name}'] = $v['contact_name'];
                $basicTypeArr['${contact_card}'] = $v['contact_card'];
                $basicTypeArr['${contact_address}'] = $v['contact_address'];
                $basicTypeArr['${contact_mobile}'] = $v['contact_mobile'];
                /*-----------------联系人信息 stop----------------*/

            } elseif ($changeCategoryName == '执行董事') {
                if (!isset($v['implement_name']) || empty($v['implement_name']) || !isset($v['implement_card']) || empty($v['implement_card'])
                    || !isset($v['implement_address']) || empty($v['implement_address']) || !isset($v['implement_mobile']) || empty($v['implement_mobile'])) {
                    $this->setError('执行董事信息填写错误');
                    return false;
                }

                /*--------股东会决议内容--------*/
                $commentRowArr = [
                    ['comentContent' => "免去{$info['oper_name']}的公司执行董事职务，选举{$v['implement_name']}为公司执行董事。"],
                    ['comentContent' => "继续聘任{$manager['name']}为公司经理。"],
                    ['comentContent' => "继续聘任{$supervisor['name']}为公司监事。"]
                ];

                /*--------执行董事信息--------*/
                $basicTypeArr['implement_name'] = $v['implement_name'];
                $basicTypeArr['implement_method'] = $generationMode;
                $basicTypeArr['implement_card'] = $v['implement_card'];
                $basicTypeArr['implement_address'] = $v['implement_address'];
                $basicTypeArr['implement_mobile'] = $v['implement_mobile'];

                /*--------董事_监事_经理信息--------*/
                $position_director_arr = [
                    [
                        'position_director_people' => $v['implement_name'],
                        'position_director_card' => $v['implement_card'],
                        'position_director_name' => '执行董事',
                        'position_director_method' => $generationMode,
                    ],
                ];
            } elseif ($changeCategoryName == '经理') {
                if (!isset($v['manager_name']) || empty($v['manager_name']) || !isset($v['manager_card']) || empty($v['manager_card'])
                    || !isset($v['manager_address']) || empty($v['manager_address']) || !isset($v['manager_mobile']) || empty($v['manager_mobile'])) {
                    $this->setError('执行董事信息填写错误');
                    return false;
                }

                /*--------股东会决议内容--------*/
                $commentRowArr = [
                    ['comentContent' => "免去{$info['oper_name']}的公司经理职务，选举{$v['manager_name']}为公司经理。"],
                    ['comentContent' => "继续聘任{$supervisor['name']}为公司监事。"]
                ];

                /*--------执行董事信息--------*/
                $basicTypeArr['manager_name'] = $v['manager_name'];
                $basicTypeArr['manager_method'] = $generationMode;
                $basicTypeArr['manager_card'] = $v['manager_card'];
                $basicTypeArr['manager_address'] = $v['manager_address'];
                $basicTypeArr['manager_mobile'] = $v['manager_mobile'];

                /*--------董事_监事_经理信息--------*/
                $position_director_arr = [
                    [
                        'position_director_people' => $v['manager_name'],
                        'position_director_card' => $v['manager_card'],
                        'position_director_name' => '经理',
                        'position_director_method' => $generationMode,
                    ],
                ];
            }

        }

        if (empty($changeTypeArr)) {
            $changeTypeArr[] = [
                'changeType' => '',
                'changeOld' => '',
                'changeNew' => ''
            ];
        }

        if (empty($recordTypeArr)) {
            $recordTypeArr[] = [
                'reocrdType' => '',
                'recordOld' => '',
                'recordNew' => ''
            ];
        }

        // 股东会决议具体内容处理
        $commentRowKeyArr = ['一、', '二、', '三、', '四、', '五、', '六、', '七、', '八、', '九、'];
        if (!empty($isZhangcheng)) $commentRowArr[]['comentContent'] = '修改公司章程相应条款。';
        if (!empty($commentRowArr)) {
            foreach ($commentRowArr as $k => &$v) {
                $v['comentContent'] = $commentRowKeyArr[$k] . $v['comentContent'];
            }
            unset($v);
        }
        if (!empty($commentRowArr_1)) {
            foreach ($commentRowArr_1 as $k => &$v) {
                $v['comentContent'] = $commentRowKeyArr[$k] . $v['comentContent'];
            }
            unset($v);
        }

        // 章程修正案
        foreach ($descRowArr as $k1 => &$v1) {
            $v1['descTitle'] = $commentRowKeyArr[$k1] . $v1['descTitle'];
        }
        unset($v1);

        foreach ($changeFunction['documentStrArr'] as &$v) {
            if (!is_file(realpath('.' . $v['template']['src']))) {
                $this->setError('模板不存在');
                return false;
            }
            //实例化, 参数传入模板文件地址
            $templateProcessor = new TemplateProcessor(realpath('.' . $v['template']['src']));
            if ($v['template']['name'] == '公司登记（备案）申请书') {
                $templateProcessor->setValues($basicTypeArr);
                $templateProcessor->cloneRowAndSetValues('changeType', $changeTypeArr);
                $templateProcessor->cloneRowAndSetValues('reocrdType', $recordTypeArr);
            } elseif ($v['template']['name'] == '经营场所承诺书') {
                $templateProcessor->setValues($basicTypeArr);
            } elseif ($v['template']['name'] == '股东会决议') {
                $basicTypeArr['shareholder'] = $basicTypeArr['shareholderOld'];
                $templateProcessor->setValues($basicTypeArr);
                $templateProcessor->cloneBlock('shareholderRow', 0, true, false, $shareholderRowArr);
                $templateProcessor->cloneBlock('commentRow', 0, true, false, $commentRowArr);
            } elseif ($v['template']['name'] == '股东决定') {
                $basicTypeArr['shareholder'] = $basicTypeArr['shareholderOld'];
                $templateProcessor->setValues($basicTypeArr);
                $templateProcessor->cloneBlock('shareholderRow', 0, true, false, $shareholderRowArr);
                $templateProcessor->cloneBlock('commentRow', 0, true, false, $commentRowArr);
            } elseif ($v['template']['name'] == '章程修正案') {
                $templateProcessor->setValues($basicTypeArr);
                $templateProcessor->cloneBlock('descRow', 0, true, false, $descRowArr);
            } elseif ($v['template']['name'] == '经营范围承诺书') {
                $templateProcessor->setValues($basicTypeArr);
            } elseif ($v['template']['name'] == '自然人投资或控股章程') {
                $templateProcessor->setValues($basicTypeArr);
                $templateProcessor->cloneBlock('rules_shareholder', 0, true, false, $rules_shareholder_arr);
                $templateProcessor->cloneBlock('rules_shareholder_row', 0, true, false, $rules_shareholder_row_arr);
            }  elseif ($v['template']['name'] == '自然人独资章程') {
                $templateProcessor->setValues($basicTypeArr);
                $templateProcessor->cloneBlock('rules_shareholder', 0, true, false, $rules_shareholder_arr);
                $templateProcessor->cloneBlock('rules_shareholder_row', 0, true, false, $rules_shareholder_row_arr);
            }  elseif ($v['template']['name'] == '公司独资章程') {
                $templateProcessor->setValues($basicTypeArr);
                $templateProcessor->cloneBlock('rules_shareholder', 0, true, false, $rules_shareholder_arr);
                $templateProcessor->cloneBlock('rules_shareholder_row', 0, true, false, $rules_shareholder_row_arr);
            } elseif ($v['template']['name'] == '法定代表人信息') {
                $templateProcessor->setValues($basicTypeArr);
            } elseif ($v['template']['name'] == '董事_监事_经理信息') {
                $position_director_arr_row = [
                    'position_director_people' => '',
                    'position_director_card' => '',
                    'position_director_name' => '',
                    'position_director_method' => '',
                ];
                // 没有的需要补全
                if (count($position_director_arr) == 1) {
                    array_push($position_director_arr, $position_director_arr_row);
                    array_push($position_director_arr, $position_director_arr_row);
                }
                if (count($position_director_arr) == 2) {
                    array_push($position_director_arr, $position_director_arr_row);
                }
                $templateProcessor->cloneBlock('position_director', 0, true, false, $position_director_arr);
            } elseif ($v['template']['name'] == '出资情况') {
                $templateProcessor->cloneRowAndSetValues('capital_name', $contributionArr);
            } elseif ($v['template']['name'] == '公司债务清偿或担保情况说明') {
                $templateProcessor->setValues($basicTypeArr);
            } elseif ($v['template']['name'] == '联络人信息') {
                $templateProcessor->setValues($basicTypeArr);
            } elseif ($v['template']['name'] == '股权转让协议') {
                $templateProcessor->setValues($equity_transfer_arr[0]);
            }  elseif ($v['template']['name'] == '股权转让协议第1份') {
                $templateProcessor->setValues($equity_transfer_arr[1]);
            }  elseif ($v['template']['name'] == '股权转让协议第2份') {
                $templateProcessor->setValues($equity_transfer_arr[2]);
            }  elseif ($v['template']['name'] == '股权转让协议第3份') {
                $templateProcessor->setValues($equity_transfer_arr[3]);
            } elseif ($v['template']['name'] == '年报承诺书') {
                $templateProcessor->setValues($basicTypeArr);
            } elseif ($v['template']['name'] == '股东会决议第二份') {
                $basicTypeArr['shareholder'] = $basicTypeArr['shareholder_1'];
                $templateProcessor->setValues($basicTypeArr);
                $templateProcessor->cloneBlock('shareholderRow', 0, true, false, $shareholderRowArr);
                $templateProcessor->cloneBlock('commentRow', 0, true, false, $commentRowArr_1);
            } elseif ($v['template']['name'] == '股东决定第二份') {
                $basicTypeArr['shareholder'] = $basicTypeArr['shareholder_1'];
                $templateProcessor->setValues($basicTypeArr);
                $templateProcessor->cloneBlock('shareholderRow', 0, true, false, $shareholderRowArr_1);
                $templateProcessor->cloneBlock('commentRow', 0, true, false, $commentRowArr_1);
            } elseif ($v['template']['name'] == '住所（经营场所）申报承诺表') {
                $templateProcessor->setValues($declarationOfCommitmentForm);
            } elseif ($v['template']['name'] == '执行董事信息') {
                $templateProcessor->setValues($basicTypeArr);
            } elseif ($v['template']['name'] == '经理信息') {
                $templateProcessor->setValues($basicTypeArr);
            }

            $suffix = 'docx';
            $realName = md5($v['template']['name']);
            $savekey = $this->getSavekey($suffix, $realName);
            $savekey = '/' . ltrim($savekey, '/');
            $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
            $destDir = ROOT_PATH . 'public' . str_replace('/', DS, $uploadDir);
            $destFile = $destDir . $realName . '.' . $suffix;
            if (!is_dir($destDir)) {
                @mkdir($destDir, 0755, true);
            }

            //保存文件
            $templateProcessor->saveAs($destFile);

            $v['realFile'] = $destFile;
        }

        return $changeFunction;
    }

    /**
     * 选择章程 自然人投资或控股章程0    自然人独资章程1    公司独资章程2
     * @param $info
     */
    public function selectConstitution($info)
    {
        return 1;
        if (count($info['partners']) > 1) return 0;
        if(mb_strlen($info['partners'][0]->name, 'UTF-8')>5) return 2;
        return 1;
    }

    /**
     * 删除无用文档
     */
    public function deleteUselessFile($changeFunction = [])
    {
        foreach ($changeFunction['documentStrArr'] as $v) {
            if (is_file($v['realFile'])) {
                unlink($v['realFile']);
            }
        }
        return true;
    }

    /**
     * 合并出模板
     */
    public function mergeTemplate($postData = [], $changeFunction = [])
    {
        /*--------文档不存在 start--------*/
        $templateArr = [];
        foreach ($changeFunction['documentStrArr'] as $v) {
            if (!$v['realFile']) {
                $this->setError("文档不存在");
                return false;
            }
            $templateArr[] = $v['realFile'];
        }
        /*--------文档不存在 start--------*/

        // 合并后文档路径
        $realName = $postData['enterprise']['name'] . '-' . $changeFunction['name'] . '文档';
        $suffix = 'docx';
        $savekey = $this->getSavekey($suffix, $realName);
        $savekey = '/' . ltrim($savekey, '/');
        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $destDir = ROOT_PATH . 'public' . str_replace('/', DS, $uploadDir);
        $destFile = $destDir . $realName . '.' . $suffix;
        if (!is_dir($destDir)) {
            @mkdir($destDir, 0755, true);
        }

        // 调用python合并文档
        $templateArrStr = implode(',', $templateArr);
        $destFileStr = urlencode($destFile);
        if (exec("python ../py/word.py {$templateArrStr} {$destFileStr}")) {
        // if (exec("sudo /www/server/panel/pyenv/bin/python3.7 /www/wwwroot/tool.xmjuncheng.com/py/word.py {$templateArrStr} {$destFileStr}")) {
            return request()->domain() . $uploadDir . $realName . '.' . $suffix;
        } else {
            $this->setError("合并文件失败");
            return false;
        }
        /*\Jupitern\Docx\DocxMerge::instance()
            ->addFiles($templateArr)
            ->save($destFile, true);*/

    }

    /**
     * 单个人或单价公司持股100%都是股东决定
     * 使用股东决定还是股东会决议
     * 为true时是股东会决议
     * @param $info
     */
    public function isDecision($info)
    {
        if (count($info['partners']) > 1) return true;
        return false;
    }

    public function getSavekey($suffix = null, $filename = null, $savekey = null)
    {
        $config = Config::get('upload');
        $md5 = md5($filename);
        $replaceArr = [
            '{year}' => date("Y"),
            '{mon}' => date("m"),
            '{day}' => date("d"),
            '{hour}' => date("H"),
            '{min}' => date("i"),
            '{sec}' => date("s"),
            '{random}' => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => substr($filename, 0, 100),
            '{suffix}' => $suffix,
            '{.suffix}' => $suffix ? '.' . $suffix : '',
            '{filemd5}' => $md5,
        ];
        $savekey = $savekey ? $savekey : $config['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        return $savekey;
    }

    /**
     * 保存企业详细信息
     */
    public function saveEnterprise($data, $postData)
    {
        if ($data) {
            db('enterprise')
                ->where("id='{$postData["companyId"]}'")
                ->update([
                    'name' => $data['name'],
                    'econ_kind' => $data['econ_kind'],
                    'regist_capi' => $data['regist_capi'],
                    'scope' => $data['scope'],
                    'addresses' => $data['address'],
                    'reg_no' => $data['reg_no'],
                    'term_start' => $data['term_start'],
                    'term_end' => $data['term_end'],
                    'belong_org' => $data['belong_org'],
                    'oper_name' => $data['oper_name'],
                    'start_date' => $data['start_date'],
                    'end_date' => $data['end_date'],
                    'status' => $data['status'],
                    'org_no' => $data['org_no'],
                    'credit_no' => $data['credit_no'],
                    'province' => $data['province'],
                    'number' => $data['id'],
                    'employees' => $data['employees'] ? json_encode($data['employees']) : '',
                    'brances' => $data['branches'] ? json_encode($data['branches']) : '',
                    'changerecords' => $data['changerecords'] ? json_encode($data['changerecords']) : '',
                    'partners' => $data['partners'] ? json_encode($data['partners']) : '',
                    'abnormal' => $data['abnormal_items'] ? json_encode($data['abnormal_items']) : '',
                    'regist_capi_new' => $data['regist_capi_new'],
                    'currency_unit' => $data['currency_unit'],
                ]);
        }
    }

    /**
     * 企业信息精确查询
     * @param $postData
     * @return bool
     */
    public function getEnterpriseDetail($postData)
    {
        $url = $postData['link'] . '?keyword=' . urlencode($postData['enterprise']['credit_no']) . '&key=' . $this->precise_information_key;
        $res = json_decode(curl_get($url), true);
        if ($res['error_code'] != 0) {
            $this->setError($res['reason']);
            return false;
        }

        return $res['result']['data'];
    }

}